package com.nx.fsm.model;

import com.nx.fsm.context.FsmRole;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程模板
 *
 * @author pfliu
 */
public class FsmTemplate {

    // 状态机类型
    private final Integer type;
    // 状态机容器
    private final Map<Long, FsmNode> fsmNodeMap = new HashMap<Long, FsmNode>();

    /**
     * 构造方法
     *
     * @param type
     * @param fsmNodes
     */
    public FsmTemplate(Integer type, List<FsmNode> fsmNodes) {
        this.type = type;
        for (FsmNode node : fsmNodes) {
            Long key = getKey(node.getSourceStatus(), node.getOpType(), node.getRole());
            fsmNodeMap.put(key, node);
        }
    }

    /**
     * 状态机类型
     *
     * @return
     */
    public Integer getType() {
        return type;
    }

    /**
     * 获得状态机配置
     *
     * @param status
     * @param opType
     * @param role
     * @return
     */
    public FsmNode getFsmNode(Integer status, Integer opType, FsmRole role) {
        Long key = getKey(status, opType, role.getId());
        return fsmNodeMap.get(key);
    }

    /**
     * getKey:(三要素定位key). <br/>
     *
     * @param status
     * @param opType
     * @param role
     * @return
     * @throws RuntimeException
     * @author liupengfei07
     */
    private static Long getKey(Integer status, Integer opType, Integer role) throws RuntimeException {
        return (Long.valueOf(role) << 32) + (Long.valueOf(status) << 16) + opType;
    }

    @Override
    public String toString() {
        return "FsmTemplate{" +
                "type=" + type +
                ", fsmNodeMap=" + fsmNodeMap +
                '}';
    }
}
